package com.iot.north.app.demo.invoke.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.iot.north.app.demo.exception.PostFailException;
import com.iot.north.app.demo.utils.JsonUtil;
import okhttp3.*;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/** 对http操作进行统一管理 */
public class HTTPClient {
  public OkHttpClient HttpClient;

  /** 初始化Http client,进行相关配置 */
  public HTTPClient() {
    this.HttpClient =
        new OkHttpClient.Builder()
            // 设置链接超时
            .connectTimeout(10, TimeUnit.SECONDS)
            // 设置写数据超时
            .writeTimeout(10, TimeUnit.SECONDS)
            // 设置读数据超时
            .readTimeout(30, TimeUnit.SECONDS)
            .build(); // 创建OkHttpClient对象
  }

  /**
   * post请求
   *
   * @param url
   * @param headerParams
   * @param bodyParams
   * @return
   * @throws PostFailException
   */
  public JsonNode post(
      String url,
      Map<String, String> headerParams,
      Map<String, Object> bodyParams)
      throws PostFailException {

    HttpUrl.Builder httpBuider = HttpUrl.parse(url).newBuilder();

    Request.Builder requestBuider =
        new Request.Builder().url(httpBuider.build()).headers(Headers.of(headerParams));

    // 此处为body为json格式的post请求
    MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
    RequestBody requestBody = RequestBody.create(JsonUtil.toJson(bodyParams), mediaType);
    requestBuider.post(requestBody);

    Response response = null;
    try {
      response = this.HttpClient.newCall(requestBuider.build()).execute();
      return JsonUtil.parse(response.body().string());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(response);
    }
    throw new PostFailException();
  }
}
